package com.interprise.shiro.realm;

import com.interprise.shiro.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class UserRealm extends AuthorizingRealm {

    /**
     * 授权过程
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = (User) principalCollection.getPrimaryPrincipal();
        /**
         * 根据用户id查询角色、权限
         */
        List<String> roles = Arrays.asList("role","role1");
        List<String> permissions = Arrays.asList("user:list","user:save");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        return info;
    }

    /**
     * 认证过程
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("###########################################");

        /**
         * 获取用户名
         */
        String username = (String)token.getPrincipal();
        User user = null;
        if("zhangsan".equalsIgnoreCase(username)){
            user = new User();
            user.setUsername("zhangsan");
            user.setPassword("21232f297a57a5a743894a0e4a801fc3");
        }

        if(user != null){
            return new SimpleAuthenticationInfo(user,user.getPassword(),super.getName());
        }
        return null;
    }
}